package com.zhiwang.planet.widget

import android.content.Context
import android.graphics.Bitmap
import android.os.Build
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.webkit.*
import android.widget.FrameLayout
import android.widget.TextView
import com.zhiwang.planet.R
import kotlinx.android.synthetic.main.layout_webview.*
import java.lang.Exception

class MasterWebView(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs) {

    lateinit var errorView: View
    var webView: WebViewEx? = null
    var currUrl: String? = null
    var loadingError = false
    private var retryFunc: (() -> Unit)? = null
    var webViewClientCallBack: WebViewClientCallBack? = null

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.MasterWebView)
        addWebView()
        if (typedArray.hasValue(R.styleable.MasterWebView_mw_error_view)) {
            errorView = LayoutInflater.from(context).inflate(/*typedArray.getResourceId(R.styleable.MasterWebView_mw_error_view, 0)*/
                    R.layout.webview_load_error_layout, null)
            val layoutParams = FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
            layoutParams.gravity = Gravity.CENTER
            errorView.visibility = View.GONE
            errorView.layoutParams = layoutParams
            addView(errorView)
            setUpRetryListener()
        }
        typedArray.recycle()
    }

    private fun setUpRetryListener() {
        errorView.findViewById<TextView>(R.id.reload_btn).setOnClickListener {
            loadingError = false
            if (retryFunc != null)
                retryFunc!!()
        }
    }

    fun setRetryListener(func: () -> Unit) {
        this.retryFunc = func
    }

    private fun addWebView() {
        try {
            webView = WebViewEx(context)

        } catch (e: Exception) {
            webView = WebViewEx(context.applicationContext)
        }
        webView?.layoutParams = FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)
        addView(webView)
        webView?.webChromeClient = WebChromeClient()
        webView?.webViewClient = InnerWebViewClient()
    }

    val TAG = "MasterWebView"

    inner class InnerWebViewClient : WebViewClient() {

        @Deprecated("")
        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            currUrl = url
            return if (webViewClientCallBack != null) webViewClientCallBack!!.shouldOverrideUrlLoading(view, url)
            else super.shouldOverrideUrlLoading(view, url)
        }

        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                currUrl = request?.url?.toString()
            }
            return if (webViewClientCallBack != null) webViewClientCallBack!!.shouldOverrideUrlLoading(view, request)
            else
                super.shouldOverrideUrlLoading(view, request)

        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            loadingError = false
            if (webViewClientCallBack != null) webViewClientCallBack!!.onPageStarted(view, url, favicon)
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            if (loadingError.not()) hideErrorView()
            if (webViewClientCallBack != null) webViewClientCallBack!!.onPageFinished(view, url)
        }

        /*override fun onLoadResource(view: WebView?, url: String?) {
            if (webViewClientCallBack != null) webViewClientCallBack!!.onLoadResource(view, url)
            super.onLoadResource(view, url)
        }

        override fun onPageCommitVisible(view: WebView?, url: String?) {
            if (webViewClientCallBack != null) webViewClientCallBack!!.onPageCommitVisible(view, url)
        }


        override fun shouldInterceptRequest(view: WebView?, url: String?): WebResourceResponse? {
          *//*  return if (webViewClientCallBack != null) webViewClientCallBack!!.shouldInterceptRequest(view, url)
            else*//*  return super.shouldInterceptRequest(view, url)
        }

        override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
           *//* return if (webViewClientCallBack != null) webViewClientCallBack!!.shouldInterceptRequest(view, request)
            else *//* return super.shouldInterceptRequest(view, request)
        }


        @Deprecated("")
        override fun onTooManyRedirects(view: WebView?, cancelMsg: Message?, continueMsg: Message?) {
            return if (webViewClientCallBack != null) webViewClientCallBack!!.onTooManyRedirects(view, cancelMsg, continueMsg)
            else super.onTooManyRedirects(view, cancelMsg, continueMsg)
        }*/


        @Deprecated("")
        override fun onReceivedError(view: WebView?, errorCode: Int, description: String?, failingUrl: String?) {
            //错误视图加载逻辑
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                return
            }

            loadingError = true
            showErrorView()
            if (webViewClientCallBack != null) webViewClientCallBack!!.onReceivedError(view, errorCode, description, failingUrl)
            else super.onReceivedError(view, errorCode, description, failingUrl)
        }

        override fun onReceivedError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) {
            if (error != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && request?.isForMainFrame == true) {
                    loadingError = true
                    showErrorView()

                }
            }
            if (webViewClientCallBack != null) webViewClientCallBack!!.onReceivedError(view, request, error)
            else super.onReceivedError(view, request, error)
        }

        /*  override fun onReceivedHttpError(view: WebView?, request: WebResourceRequest?, errorResponse: WebResourceResponse?) {
              if (webViewClientCallBack != null) webViewClientCallBack!!.onReceivedHttpError(view, request, errorResponse)
              else super.onReceivedHttpError(view, request, errorResponse)
          }

          override fun onFormResubmission(view: WebView?, dontResend: Message?, resend: Message?) {
              if (webViewClientCallBack != null) webViewClientCallBack!!.onFormResubmission(view, dontResend, resend)
              else super.onFormResubmission(view, dontResend, resend)
          }

          override fun doUpdateVisitedHistory(view: WebView?, url: String, isReload: Boolean) {
              if (webViewClientCallBack != null) webViewClientCallBack!!.doUpdateVisitedHistory(view, url, isReload)
              else super.doUpdateVisitedHistory(view, url, isReload)
          }

          override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
              if (webViewClientCallBack != null) webViewClientCallBack!!.onReceivedSslError(view, handler, error)
              else super.onReceivedSslError(view, handler, error)
          }

          override fun onReceivedClientCertRequest(view: WebView?, request: ClientCertRequest?) {
              if (webViewClientCallBack != null) webViewClientCallBack!!.onReceivedClientCertRequest(view, request)
              else super.onReceivedClientCertRequest(view, request)
          }

          override fun onReceivedHttpAuthRequest(view: WebView?, handler: HttpAuthHandler?, host: String?, realm: String?) {
              if (webViewClientCallBack != null) webViewClientCallBack!!.onReceivedHttpAuthRequest(view, handler, host, realm)
              else super.onReceivedHttpAuthRequest(view, handler, host, realm)
          }

          override fun shouldOverrideKeyEvent(view: WebView?, event: KeyEvent?): Boolean {
              return if (webViewClientCallBack != null) webViewClientCallBack!!.shouldOverrideKeyEvent(view, event)
              else super.shouldOverrideKeyEvent(view, event)
          }

          override fun onUnhandledKeyEvent(view: WebView?, event: KeyEvent?) {
              if (webViewClientCallBack != null) webViewClientCallBack!!.onUnhandledKeyEvent(view, event)
              else super.onUnhandledKeyEvent(view, event)
          }

          override fun onScaleChanged(view: WebView?, oldScale: Float, newScale: Float) {
              if (webViewClientCallBack != null) webViewClientCallBack!!.onScaleChanged(view, oldScale, newScale)
              else super.onScaleChanged(view, oldScale, newScale)
          }

          override fun onReceivedLoginRequest(view: WebView, realm: String?, account: String?, args: String?) {
              if (webViewClientCallBack != null) webViewClientCallBack!!.onReceivedLoginRequest(view, realm, account, args)
              else super.onReceivedLoginRequest(view, realm, account, args)
          }

          override fun onRenderProcessGone(view: WebView?, detail: RenderProcessGoneDetail?): Boolean {
              return if (webViewClientCallBack != null) webViewClientCallBack!!.onRenderProcessGone(view, detail)
              else super.onRenderProcessGone(view, detail)
          }

          override fun onSafeBrowsingHit(view: WebView?, request: WebResourceRequest?, threatType: Int, callback: SafeBrowsingResponse?) {
              if (webViewClientCallBack != null) webViewClientCallBack!!.onSafeBrowsingHit(view, request, threatType, callback)
              else super.onSafeBrowsingHit(view, request, threatType, callback)
          }*/

    }

    fun showErrorView() {
        webView?.visibility = View.INVISIBLE
        errorView.visibility = View.VISIBLE
    }


    fun hideErrorView() {
        webView?.visibility = View.VISIBLE
        errorView.visibility = View.GONE
    }

    fun isFailed() = loadingError
}